const app = getApp();
const {
  readIDCard,
  IDCardTypes
} = requirePlugin('thePlugin')
Page({
  data: {
    appName: app.globalData.appName,
    names: '',
    idcards: '',
    emailss: '',
    type: 'avatar', //type参数为”emblem“，或”avatar“
    imageOutput: 'roi', //imageOutput参数为“global”或者“roi”
    codecard1: "",
    codecard2: "",
    codecard3: "",
    student: "",
    ishow: false,
    face: {},
    back: {},
  },
  onLoad() {

  },
  nametit(e) {
    console.log("111", e)
    let idcard = {};
    idcard.names = e.detail.value;
    idcard.idcards = this.data.idcards
    my.setStorage({
      key: 'idcard',
      data: idcard,
    })
  },
  emails(e) {
    console.log("111", e)
    let idcard = {};
    idcard.names = this.data.names;
    idcard.idcards = this.data.idcards;
    idcard.emailss = e.detail.value;
    this.setData({
      emailss: e.detail.value
    })
    my.setStorage({
      key: 'idcard',
      data: idcard,
    })
  },

  numtit(e) {
    console.log("111", e)
    let idcard = {};
    idcard.names = this.data.names;
    idcard.idcards = e.detail.value;
    my.setStorage({
      key: 'idcard',
      data: idcard,
    })
  },
  onShow() {
    this.get_mrg()
  },

  get_mrg() {
    let user = my.getStorageSync({
      key: 'user'
    }).data;
    console.log("储存信息1", user)
    this.setData({
      user: user,
    })
    if (user != null) {


      if (user.idCardUrl) {
        let arr = JSON.parse(user.idCardUrl)
        console.log("储存信息", arr)

        console.log("储存信息11", arr)

        let app = {
          codecard1: '',
          codecard2: '',
          codecard3: '',

          ishow: true
        }
        arr.forEach((item, index) => {
          if (item.includes('.UNKNOWN') || item == '') {
            //console.log("图片无法识别",item)
            arr[index] = ''
            app.ishow = false
          }
        })
        app.codecard1 = arr[0]
        app.codecard2 = arr[1]
        app.codecard3 = arr[2]

        if (user.contractUserInfo) {
          const idInfo = JSON.parse(user.contractUserInfo)
          this.setData({
            face: idInfo.face,
            bace: idInfo.back,
          })
        }

        this.setData({
          ...app,
          ...{
            names: user.name,
            idcards: user.idCard,
            emailss: user.email
          }
        })
        //console.log("=============>>idcard",arr)
      }
    }
  },

  // 上传图片
  onSubmit() {

    let res = my.getStorageSync({
      key: 'user'
    }).data;
    console.log(res)

    if (!this.data.codecard1 || !this.data.codecard2 || !this.data.codecard3 ) {
      my.alert({
        content: '请补全正反面身份证手持身份证信息以及邮箱信息！',
        success: () => {

        }
      });
      return false
    }


   
    if (!this.data.emailss) {
      my.alert({
        content: '亲亲，辛苦补全邮箱信息哦！',
        success: () => {

        }
      });
      return false
    } else {
      if (!this.isEmailAvailable(this.data.emailss)) {
        my.alert({
          content: '邮箱格式错误！',
          success: () => {

          }
        });
        return false
      }
    }
    let arr = [this.data.codecard1, this.data.codecard2, this.data.codecard3];

    console.log(this.data.face, '3333')
    let data = {
      idCardUrl: JSON.stringify(arr),
      email: this.data.emailss,
      name: this.data.face.data.name ? this.data.face.data.name.data : '',
      idCard: this.data.face.data.num ? this.data.face.data.num.data : '',
      contractUserInfo: this.data.face.data.name ? JSON.stringify({
        face: this.data.face,
        back: this.data.back
      }) : ''
    }
    console.log(data, 'sddddddddddd')
    // return;
    app.user.saveidCard(data)
      .then(json => {
        //console.log(json)
        if (json.code == 200) {
          let user = this.data.user
          user.idCardUrl = JSON.stringify(arr)
          //console.log(user.idCardUrl)
          this.setData({
            user: user,
            ishow: true
          })
          my.setStorage({
            key: 'user',
            data: user,
          })
          my.alert({
            content: json.msg,
            success: () => {
              //console.log("")
              my.navigateBack();
            }
          });
        }
      })
  },
  isEmailAvailable(obj) {
    let email = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    if (!email.test(obj)) {
      return false;
    }
    return true;
  },
  onUpload(e) {
    const name = e.target.dataset.image;
    //console.log(e);

    my.chooseImage({
      sourceType: ['camera', 'album'],
      count: 1,
      success: (res) => {
        console.log("图片", res)
        const path = res.apFilePaths[0]
        app.other.uploadFile(path)
          .then((res) => {
            console.log("==============111", JSON.parse(res.data))
            if (JSON.parse(res.data).code == 200) {
              let str = JSON.parse(res.data).data
              const r = str.split('').reverse().join('');
              const p = r.search(/\./)
              str = r.substring(0, p).split('').reverse().join('');
              //console.log(str)
              if (['jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG'].includes(str)) {
                my.showToast({
                  content: '上传成功',
                })
                this.setData({
                  [name]: JSON.parse(res.data).data,
                })
              } else if (['UNKNOWN', 'unknown'].includes(str)) {
                my.showToast({
                  content: '图片格式错误，请重新上传',
                })
              } else {
                my.showToast({
                  content: '图片无法识别，请重新上传',
                })
              }
              //console.log(['jpg', 'jpeg', 'png'].includes(str))
            } else {
              my.showToast({
                content: '图片错误，请重新上传', // 文字内容
              });
            }
          })
      },
      fail: () => {
        my.showToast({
          content: '选择错误,请重新选择', // 文字内容
        });
      }
    })
  },
  onUploads() {
    var that = this;
    readIDCard({
        bizId: '身份证上传',
        type: IDCardTypes.FRONT
      })
      .then((res) => {
        console.log("正面信息", res)

        if (res.error) {

          // 用户取消
          if (res.error.error === 11) {
            return;
          }
          res.error = '请重新上传身份证正面照片未识别成功。';
          my.alert({
            content: res.error
          })
          return;
        }


        console.log('正面信息', res.image)
        const userInfo = res

        that.setData({
          names: res.data.name.data,
          idcards: res.data.num.data
        })
        let idcard = {};
        idcard.names = res.data.name.data;
        idcard.idcards = res.data.num.data;
        my.setStorage({
          key: 'idcard',
          data: idcard,
        })

        app.other.uploadFile(res.image)
          .then((res) => {
            console.log("photo",JSON.parse(res.data).data);
            const idCardUrl = JSON.parse(res.data).data
            userInfo.image = idCardUrl
            delete userInfo['array']


            that.setData({
              codecard1: idCardUrl,
              // 人脸正面信息
              face: userInfo
            })

          })


      })


  },
  onUploadss() {
    var that = this;
    readIDCard({
        bizId: '身份证上传',
        type: IDCardTypes.BACK
      })
      .then((res) => {
        console.log('反面信息', res)

        if (res.error) {
          // 用户取消
          if (res.error.error === 11) {
            return;
          }
          res.error = '请重新上传身份证反面照片。';
          my.alert({
            content: res.error
          })

          return;
        }
        const userInfo = res

        // my.alert({content: JSON.stringify(res)} )

        app.other.uploadFile(res.image)
          .then((res) => {


            const idCardUrl = JSON.parse(res.data).data
            userInfo.image = idCardUrl
            delete userInfo['array']

            that.setData({
              codecard2: idCardUrl,
              // 人脸反面面信息
              back: userInfo
            })

          })


      }).catch(e => {
        console.log("222", e)

        my.showToast({
          content: e.msg ? e.msg : '网络异常'
        });
      })


  },

});